package com.wyj.chat.websocket_chat.websocket.socket;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.*;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Create by wyj on 2018/4/13
 */
@ServerEndpoint(value = "/chatSocket")
@Component
public class ChatSocket {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的ChatSocket对象。
    private static CopyOnWriteArraySet<ChatSocket> webSocketSet = new CopyOnWriteArraySet<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    // 文件名
    private String filename;
    private String picname;
    private String user;
    private String toUser;
    private String[] members;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        String[] info = message.split(",");
        String userInfo = info[0].split(":")[1];
        String toUserInfo = info[1].split(":")[1];
        this.toUser = toUserInfo;
        this.user = userInfo;
        if(message.contains("groupChat--")) {
            String[] members = toUserInfo.split("--")[1].split("-");
            this.members = members;
        }
        if(message.contains("fileName")) {
            int index = message.lastIndexOf("fileName:");
            this.filename = message.substring(index+9);
            return;
        }
        if(message.contains("picName")) {
            int index = message.lastIndexOf("picName:");
            this.picname = message.substring(index+8);
            return;
        }

        if(message.contains("groupChat--")) {
            for (String member:members) {
                if (!member.equals(user)) {
                    for (ChatSocket item : webSocketSet) {
                        try {
                            item.sendMessage("user:"+user+",toUser:"+ member +",text:"+info[2].split(":")[1]);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("user:"+user+",toUser:"+ member +",text:"+info[2].split(":")[1]);
                }
            }
            return;
        }

        //群发消息
        for (ChatSocket item : webSocketSet) {
            try {
                item.sendMessage("user:"+user+",toUser:"+toUser+",text:"+info[2].split(":")[1]);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 二进制文件
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(byte[] message,Session session) {
        System.out.println("收到2进制流");
        try {
            // 获得输出流
            if(picname!=null){
                String realPath = "D:\\software\\IntelliJIDEA\\IdeaProjects\\websocket_chat\\springboot_websocketChat\\src\\main\\resources\\static\\img";
                String filePath = realPath+"/"+picname;
                File file = new File(filePath);
                OutputStream os = new FileOutputStream(file);
                // 输出文件
                os.write(message, 0, message.length);
                // 释放资源
                os.flush();
                os.close();
                String getPic = "/img/" + picname;
                // 群聊
                if (members!=null) {
                    for (String member:members) {
                        if (!member.equals(user)) {
                            for (ChatSocket item : webSocketSet) {
                                try {
                                    item.sendMessage("user:" + user + ",toUser:" + member + ",getPic:" + getPic);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    picname=null;
                    members=null;
                    return;
                }
                for (ChatSocket item : webSocketSet) {
                    try {
                        item.sendMessage("user:"+user+",toUser:"+toUser+",getPic:" + getPic);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                picname=null;
            }

            if (filename!=null) {
                String realPath = "D:\\software\\IntelliJIDEA\\IdeaProjects\\websocket_chat\\springboot_websocketChat\\src\\main\\resources\\static\\file";
                String filePath = realPath+"/"+filename;
                File file = new File(filePath);
                OutputStream os = new FileOutputStream(file);
                // 输出文件
                os.write(message, 0, message.length);
                // 释放资源
                os.flush();
                os.close();
                String getFile = "/file/" + filename;
                if (members!=null) {
                    for (String member:members) {
                        if (!member.equals(user)) {
                            for (ChatSocket item : webSocketSet) {
                                try {
                                    item.sendMessage("user:"+user+",toUser:"+member+",getFile:" + getFile);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    members=null;
                    filename=null;
                    return;
                }

                for (ChatSocket item : webSocketSet) {
                    try {
                        item.sendMessage("user:"+user+",toUser:"+toUser+",getFile:" + getFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                filename=null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            user=null;
            toUser=null;
        }
    }

    /**
     * 发生错误时调用
     @OnError
     */
     public void onError(Session session, Throwable error) {
         System.out.println("发生错误");
         error.printStackTrace();
     }

     public void sendMessage(String message) throws IOException {
         this.session.getBasicRemote().sendText(message);
     }

    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (ChatSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        ChatSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        ChatSocket.onlineCount--;
    }

}
